package com.yuxl.ai.knowledgeText.service;

import com.yuxl.ai.knowledgeText.entity.AiKnowledgeText;
import com.yuxl.ai.knowledgeText.repository.AiKnowledgeTextEmbeddingRepository;
import com.yuxl.ai.knowledgeText.repository.AiKnowledgeTextRepository;
import com.yuxl.common.auth.utils.JwtUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;

/**
 * @Author : yuxl
 * @create 2025/7/10 下午6:09
 */
@Slf4j
@Service
public class AiKnowledgeTextService {
    @Resource
    private AiKnowledgeTextRepository aiKnowledgeTextRepository;
    @Resource
    private JwtUtil jwtUtil;


    public Flux<AiKnowledgeText> findAll() {
        return aiKnowledgeTextRepository.findAll();
    }

    public Mono<AiKnowledgeText> findById(Long id) {
        return aiKnowledgeTextRepository.findById(id)
                .defaultIfEmpty(new AiKnowledgeText());
    }

    public Mono<Void> deleteById(Long id) {
        return aiKnowledgeTextRepository.deleteById(id);
    }

    public Mono<AiKnowledgeText> create(AiKnowledgeText entity) {
        return jwtUtil.getCurrentUser()
                .flatMap(user ->{
                    entity.setCreateBy(user.id());
                    entity.setUpdateBy(user.id());
                    entity.setCreateTime(LocalDateTime.now());
                    entity.setUpdateTime(LocalDateTime.now());
                    return aiKnowledgeTextRepository.save(entity);
                });
    }

    public Mono<Integer> count(AiKnowledgeText entity) {
        return aiKnowledgeTextRepository.count(entity);
    }


    public Flux<AiKnowledgeText> page(AiKnowledgeText entity, int page, int size) {
        long offset = (long) (page - 1) * size;
        return aiKnowledgeTextRepository.page(entity, size, offset);
    }


    public Flux<AiKnowledgeText> list(AiKnowledgeText entity) {
        return aiKnowledgeTextRepository.list(entity);
    }

    public Mono<AiKnowledgeText> updateById(AiKnowledgeText entity) {
        return jwtUtil.getCurrentUser()
                .flatMap(user ->{
                    entity.setUpdateBy(user.id());
                    entity.setUpdateTime(LocalDateTime.now());
                    return aiKnowledgeTextRepository.updateById(entity)
                            .flatMap(rows -> rows > 0 ? aiKnowledgeTextRepository.findById(entity.getId()) : Mono.empty());
                });
    }


}
